<template>
  <a-card :bordered="false" style="margin-top: 24px" title="业务管理" class="ant-pro-components-tag-select">
    <div class="table-operator">
      <a-button type="primary" class="btn-success" icon="plus" @click="handleAdd()">新建</a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
    >
      <span slot="name" slot-scope="text,record">
        {{ text }}
        <a-tag v-for="(item, index) in record.tags" :key="index">
          {{ item }}
        </a-tag>
      </span>

      <span slot="maxLifeDay" slot-scope="text"> 
        <template v-if="text">{{ text }}天</template>  
        <template v-else>-</template>  
      </span>

      <!-- <a-table
        slot="expandedRowRender"
        slot-scope="record"
        :columns="childrenColumns"
        :data-source="record.child"
        :pagination="false"
      >
        <span slot="maxLifeDay" slot-scope="subText"> {{ subText }}天 </span>
        <span slot="operation" slot-scope="subText, subRecord" class="table-operation">
          <a @click="handleSubEdit(record, subRecord)">
            <a-tooltip>
              <template slot="title"> 修改 </template>
              修改
            </a-tooltip>
          </a>
          <a-divider type="vertical" />
          <a @click="showSubDeleteModal(subRecord)">
            <a-tooltip>
              <template slot="title"> 删除 </template>
              删除
            </a-tooltip>
          </a>
        </span>
      </a-table> -->

      <span slot="action" slot-scope="record">
        <!-- 二级业务和一级业务调用不同的弹框 -->
        <template v-if="record.isChild">
          <a @click="handleSubEdit(record)">
            <a-tooltip>
              <template slot="title"> 修改 </template>
              修改
            </a-tooltip>
          </a>
          <a-divider type="vertical" />
          <a @click="showSubDeleteModal(record)">
            <a-tooltip>
              <template slot="title"> 删除 </template>
              删除
            </a-tooltip>
          </a>
        </template>
        <!-- 二级业务和一级业务调用不同的弹框 -->
        <template v-else>
          <a @click="handleEdit(record)">
            <a-tooltip>
              <template slot="title"> 修改 </template>
              修改
            </a-tooltip>
          </a>
          <a-divider type="vertical" />
          <a @click="showDeleteModal(record)">
            <a-tooltip>
              <template slot="title"> 删除 </template>
              删除
            </a-tooltip>
          </a>
          <a-divider type="vertical" />
          <a @click="handleSubAdd(record)">
            <a-tooltip>
              <template slot="title"> 添加子业务 </template>
              添加子业务
            </a-tooltip>
          </a>
        </template>
       
      </span>
    </a-table>
    <category-create-modal ref="categoryCreateModal" @ok="handleOk" />
    <category-edit-modal ref="categoryEditModal" @ok="handleOk" />
    <category-create-sub-modal ref="categoryCreateSubModal" @ok="handleOk" />
    <category-edit-sub-modal ref="categoryEditSubModal" @ok="handleOk" />
  </a-card>
</template>

<script>
import { sqlSelect, sqlFindOne, sqlDelete } from '@/api/sql'
import CategoryCreateModal from './modules/category/createModal'
import CategoryEditModal from './modules/category/editModal'
import CategoryCreateSubModal from './modules/category/createSubModal'
import CategoryEditSubModal from './modules/category/editSubModal'

export default {
  name: 'CategoryList',
  components: {
    CategoryCreateModal,
    CategoryEditModal,
    CategoryCreateSubModal,
    CategoryEditSubModal
  },
  data () {
    return {
      pagination: {
        page: 0, // 请求参数
        defaultPageSize: 10,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => this.$t('pagination.total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      },
      loading: false,
      columns: [
        {
          title: '业务名称',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '业务索引',
          dataIndex: 'codeFormat',
          key: 'codeFormat'
        },
        // {
        //   title: '标签',
        //   dataIndex: 'tags',
        //   key: 'tags',
        //   scopedSlots: { customRender: 'tags' }
        // },
        {
          title: '日志保留天数',
          dataIndex: 'max_life_day',
          key: 'max_life_day',
          scopedSlots: { customRender: 'maxLifeDay' }
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '创建人',
          dataIndex: 'create_by',
          key: 'create_by'
        },
        {
          title: '操作',
          key: 'action',
          width: 210,
          scopedSlots: { customRender: 'action' }
        }
      ],
      childrenColumns: [
        {
          title: '二级业务名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '二级业务索引',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '日志保留天数',
          dataIndex: 'max_life_day',
          key: 'max_life_day',
          scopedSlots: { customRender: 'maxLifeDay' }
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: []
    }
  },
  mounted () {
    this.getData(this.pagination.page, this.pagination.pageSize)
  },
  methods: {
    /**
     * 切换分页，重新请求数据
     */
    handleTableChange (pagination, filters, sorter) {
      this.pagination.pageSize = pagination.pageSize
      this.pagination.page = (pagination.current - 1) * this.pagination.pageSize
      this.getData(this.pagination.page, this.pagination.pageSize)
    },

    /**
     * 获取数据
     */
    async getData (page, size) {
      const result = await this.getList(page, size)
      const children = await this.getCategorySubList(result)
      // 组装二级业务
      result.forEach((item, index) => {
        item.codeFormat = item.code
        item.children = children[index]
      })

      this.data = result

      this.pagination.total = await this.getTotal()
      console.log('this.data', this.data)
      console.log(' this.pagination.total', this.pagination.total)
    },

    /**
     * 获取列表数据
     */
    getList (page, size) {
      const params = {
        sql: `select * from t_category order by id desc limit ${page},${size}`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            // 标签string转objetct
            res.forEach((item, index) => {
              item.key = index
              item.tags = item.tags ? item.tags.split(',') : ''
            })
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 获取数据总数
     */
    getTotal () {
      const params = {
        sql: 'select count(*) as total from t_category'
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res.total)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 新建
     */
    handleAdd () {
      this.$refs.categoryCreateModal.init()
    },

    /**
     * 修改
     */
    handleEdit (record) {
      this.$refs.categoryEditModal.init(record.id)
    },

    /**
     * 新建二级业务
     */
    handleSubAdd (record) {
      this.$refs.categoryCreateSubModal.init(record)
    },

    /**
     * 编辑二级业务
     */
    handleSubEdit (record) {
      console.log(record.pid)
      var parent = this.data.filter(item => (record.pid === item.id))[0]

      console.log(parent)
      console.log(record)
      this.$refs.categoryEditSubModal.init(parent, record)
    },

    /**
     * 删除弹框
     */
    showDeleteModal (record) {
      console.log('record', record)
      // 当前业务存在子业务，不能删除
      if (record.children.length > 0) {
        this.$notification['error']({
          message: '提示',
          description: '当前业务存在子业务，不能删除'
        })
        return
      }
      this.$confirm({
        title: '提示',
        content: '确定删除数据吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          console.log('OK')
          this.delete(record['id']).then((res) => {
            this.$notification['success']({
              message: '提示',
              description: '数据删除成功'
            })
            // 重新请求数据
            this.getData(this.pagination.page, this.pagination.pageSize)
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },

    /**
     * 删除数据
     */
    delete (id) {
      const params = {
        sql: `delete from t_category where id=${id}`
      }
      return new Promise((resolve, reject) => {
        sqlDelete(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 刷新数据
     */
    handleOk () {
      console.log('刷新数据')
      this.getData(this.pagination.page, this.pagination.pageSize)
    },

    /**
     * 获取二级业务
     * 根据一级业务id获取对应的二级业务
     */
    getCategorySubList (result) {
      var arr = []
      result.forEach((item) => {
        const params = {
          sql: `select * from t_category_sub where pid = ${item.id} order by id desc`
        }
        arr.push(
          new Promise((resolve, reject) => {
            sqlSelect(params).then(
              (res) => {
                res.forEach((subItem, index) => {
                  subItem.key = subItem.pid + index + 5
                  // 组装父级code
                  subItem.codeFormat = item.code + '_' + subItem.code
                  // 标记这是二级业务
                  subItem.isChild = true
                })
                resolve(res)
              },
              (error) => {
                console.log(error)
                resolve([])
              }
            )
          })
        )
      })
      return Promise.all(arr).then(function (res) {
        return res
      })
    },

    /**
     * 删除弹框
     */
    showSubDeleteModal (record) {
      console.log(record)
      this.$confirm({
        title: '提示',
        content: '确定删除数据吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          console.log('OK')
          this.deleteSub(record['id']).then((res) => {
            this.$notification['success']({
              message: '提示',
              description: '数据删除成功'
            })
            // 重新请求数据
            this.getData(this.pagination.page, this.pagination.pageSize)
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },

    /**
     * 删除数据
     */
    deleteSub (id) {
      const params = {
        sql: `delete from t_category_sub where id=${id}`
      }
      return new Promise((resolve, reject) => {
        sqlDelete(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    }
    
  }
}
</script>

<style lang="less" scoped>
</style>
